<template>
  <div class="my-editor-container" style="border: 1px solid #ccc; overflow: hidden; ">
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" style="border-bottom: 1px solid #ccc" />
    <Editor v-bind="$attrs" v-model="valueHtml" :defaultConfig="editorConfig"
      :style="{ 'overflow-y': 'hidden', 'overflow-x': 'auto','height':'calc(100% - 85px)' }" @onCreated="handleCreated" />
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});

const editorRef = shallowRef();
const valueHtml = ref("");

const toolbarConfig = {
  //删除工具栏中不需要的选项比如视频就是group-video
  excludeKeys: ["group-video", "full-screen", "emotion",],
};

onMounted(() => {
  setTimeout(() => {
    valueHtml.value = props.content;
  }, 0);
});

watch(
  () => props.content,
  (newVal) => {
    valueHtml.value = newVal;
  }
);


const ExpressIp = "http://localhost:32068"
const uploadImg = async (file, insertFn) => {
  const imgData = new FormData(); // 创建form对象
  imgData.append("file", file); // 通过append向form对象添加数据
  imgData.append("namespace", "note");
  console.log("imgData", imgData);
  console.log("file", file);

  fetch(`${ExpressIp}/upload`, {
    method: "POST",
    body: imgData,
  })
    .then((res) => res.json())
    .then((res) => {
      console.log("res", res);
      insertFn(ExpressIp + res.data.url);
    })
    .catch((err) => {
      console.log("err", err);
    });

};


const editorConfig = {
  placeholder: "请输入内容...",
  // 取消清空后默认的 <p><br></p>
  defaultContent: [],
  MENU_CONF: {
    // 禁用本地图片上传，保留网络图片插入能力
    uploadImage: {
      customUpload: uploadImg, // 空函数禁用本地上传
    },
  },
};


const getContext = () => {
  return valueHtml.value == '<p><br></p>' ? '' : valueHtml.value;
};

defineExpose({
  getContext,
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped>
::v-deep .w-e-text-container table td,
.w-e-text-container table th {
  word-break: break-all !important
}
::v-deep  .editor-wrapper{
  height: calc(100% - 20px);
}
</style>
